# -*- coding: utf-8 -*-

# 使用了 [PyAutoGUI==0.9.54]，遵循其 [BSD License] 许可证，原始代码来源：[https://github.com/asweigart/pyautogui]
# 使用了 [pywin32==305.1]，遵循其 [Python Software Foundation License] 许可证，原始代码来源：[https://github.com/mhammond/pywin32]
# 使用了 [pynput==1.8.1]，遵循其 [GNU Lesser General Public License v3 (LGPLv3)] 许可证，原始代码来源：[https://github.com/moses-palmer/pynput]

import tkinter,os
import tkinter.font as tkFont
from tkinter.filedialog import askopenfilename
from win32api import GetSystemMetrics
import re
import base64
import pyautogui
import pynput
import sys
import datetime

# pyautogui.moveTo(x,y,duration=dura)
# pyautogui.press(key)
# pyautogui.click(clicks=times,interval=0.1,button=but)
# pyautogui.typewrite("hello")
# pyautogui.keyDown(key_name)
# pyautogui.keyUp(key_name)
# pyautogui.hotkey('ctrl','c')
# pyautogui.mouseDown(x,y,button='left')
# pyautogui.mouseUp(x,y,button='left')
#alt +space+x 窗口最大化.
#win+m 最小化所有窗口.
def do_script(cmd):
    # pyautogui.PAUSE=0.1
    if(cmd.startswith("m-c:")):
        ptn=r"\(([0-9]*),\s([0-9]*)\)-Button.([^-]*)-(True|False)"
        a=re.findall(ptn,cmd)
        x=a[0][0]
        y=a[0][1]
        b=a[0][2]
        p=a[0][3]
        if(p=="True"):
            pyautogui.moveTo(int(x),int(y),duration=1)
            pyautogui.mouseDown(int(x),int(y),button=b,duration=0.2)
        else:
            pyautogui.moveTo(int(x),int(y),duration=1)
            pyautogui.mouseUp(int(x),int(y),button=b,duration=0.2)
    elif(cmd.startswith("k-p:")):#按下某个键.
        cmd=cmd.replace(u'k-p:',u'')
        if(cmd.startswith("Key.")):
            cmd=cmd.replace(u'Key.',u'')
            if(cmd=="alt_gr"):
                pyautogui.keyDown("altright")
            elif(cmd=="alt_l"):
                pyautogui.keyDown("altleft")
            elif(cmd=="ctrl_l"):
                pyautogui.keyDown("ctrlleft")
            elif(cmd=="ctrl_r"):
                pyautogui.keyDown("ctrlright")
            elif(cmd=="shift_l"):
                pyautogui.keyDown("shiftleft")
            elif(cmd=="shift_r"):
                pyautogui.keyDown("shiftright")
            elif(cmd=="page_down"):
                pyautogui.keyDown("pagedown")
            elif(cmd=="page_up"):
                pyautogui.keyDown("pageup")
            elif(cmd=="menu"):
                pyautogui.keyDown("winleft")
            elif(cmd=="cmd"):
                pyautogui.keyDown("command")
            elif(cmd=="caps_lock"):
                pyautogui.keyDown("capslock")
            else:
                cmd=cmd.replace(u'\'',u'')
                pyautogui.keyDown(cmd)
        else:
            if(cmd==r"'"):
               pyautogui.keyDown("'")
            elif(cmd==r'\\'):
                pyautogui.keyDown(r'\\')
            else:
                cmd=cmd.replace(u'\'',u'')
                pyautogui.keyDown(cmd)
    elif(cmd.startswith("k-r:")):
        cmd=cmd.replace(u'k-r:',u'')
        if(cmd.startswith("Key.")):
            cmd=cmd.replace(u'Key.',u'')
            if(cmd=="alt_gr"):
                pyautogui.keyUp("altright")
            elif(cmd=="alt_l"):
                pyautogui.keyUp("altleft")
            elif(cmd=="ctrl_l"):
                pyautogui.keyUp("ctrlleft")
            elif(cmd=="ctrl_r"):
                pyautogui.keyUp("ctrlright")
            elif(cmd=="shift_l"):
                pyautogui.keyUp("shiftleft")
            elif(cmd=="shift_r"):
                pyautogui.keyUp("shiftright")
            elif(cmd=="page_down"):
                pyautogui.keyUp("pagedown")
            elif(cmd=="page_up"):
                pyautogui.keyUp("pageup")
            elif(cmd=="menu"):
                pyautogui.keyUp("winleft")
            elif(cmd=="cmd"):
                pyautogui.keyUp("command")
            elif(cmd=="caps_lock"):
                pyautogui.keyUp("capslock")
            else:
                cmd=cmd.replace(u'\'',u'')
                pyautogui.keyUp(cmd)
        else:
            if(cmd==r"'"):
               pyautogui.keyUp("'")
            elif(cmd==r'\\'):
                pyautogui.keyUp('\\')
            else:
                cmd=cmd.replace(u'\'',u'')
                pyautogui.keyUp(cmd)
    print(cmd)
def limit_str_len(stri,length=9):#限制字符长度.
    if(len(stri)>length):
        stri=stri[0:length]
    return(stri)
def set_window(x,y):#function to set the window to the x,y size, and in the middle. needed.
    screenwidth=GetSystemMetrics(0)#获取屏幕宽度大小像素.
    screenheight=GetSystemMetrics(1)#获取屏幕高度大小像素.1
    size='%dx%d+%d+%d'%(x,y,(screenwidth-x)/2,(screenheight-y)/2)
    return(size)
def get_screen_pixel():#function to get the screen size. needed.
    return(GetSystemMetrics(0),GetSystemMetrics(1))#返回像素大小.
class GUI(tkinter.Frame):
    def __set_grid_cell_size(self):#set window size, base line and unit.
        (self.__x_unit,self.__y_unit)=get_screen_pixel()#获取屏幕总像素.
        self.__x_unit/=self.SCREEN_CELL_NUMBER_X#设置网格横向大小.
        self.__y_unit/=self.SCREEN_CELL_NUMBER_Y#设置网格纵向大小.
        self.__x_unit_int=int(self.__x_unit)#网格横向大小取整.
        self.__y_unit_int=int(self.__y_unit)#网格纵向大小取整.
    def __set_grid_cell_number(self,x,y):#设置grid数量.
        self.__x_num=x
        self.__y_num=y
    def get_GUI_size(self):#根据像素、网格数量确定窗口大小.
        return(self.__x_unit_int*(self.__x_num),self.__y_unit_int*(self.__y_num))
    def __create_frames(self):#用Frame来填充整个GUI控件.
        for i in range(1,self.__x_num+1):
            for j in range(1,self.__y_num+1):
                c=tkinter.Frame(self,width=self.__x_unit_int,height=self.__y_unit_int,bg=self.BACK_COLOR)
                c.grid(row=j,column=i,sticky='WSEN')
    def __set_font(self):
        self.ft=tkFont.Font(family='宋体',size=-self.__y_unit_int)#自动调整字体大小.
    def __set_button(self):
        self.__bsx=2
        self.__bsy=2
        self.__button_column=self.__x_num-self.__bsx+1
    def __get_button_column(self):
        return self.__button_column
    def __set_label(self):#set the label base size and base line.
        self.__lsx=3
        self.__lsy=2
        self.__label_column=self.__x_num-self.__lsx
    def __get_label_column(self):
        return self.__label_column
    def create_buttons(self):#Buttons.
        self.BUTTON1=tkinter.Button(self,height=1,bg=self.LABEL_COLOR_1,text="导入",command=self.open_file,font=self.ft)
        self.BUTTON1.grid(row=1,column=self.__get_button_column(),rowspan=self.__bsy,columnspan=self.__bsx,sticky='WSEN')

        self.BUTTON1=tkinter.Button(self,height=1,bg=self.LABEL_COLOR_1,text="录入",command=self.start_record,font=self.ft)
        self.BUTTON1.grid(row=3,column=self.__get_button_column(),rowspan=self.__bsy,columnspan=self.__bsx,sticky='WSEN')

        self.BUTTON2=tkinter.Button(self,height=1,bg=self.LABEL_COLOR_2,text="执行",command=self.do_action,font=self.ft)
        self.BUTTON2.grid(row=5,column=self.__get_button_column(),rowspan=self.__bsy,columnspan=self.__bsx,sticky='WSEN')

        self.BUTTON3=tkinter.Button(self,height=1,bg=self.LABEL_COLOR_1,text="重复",command=self.do_repeat,font=self.ft)
        self.BUTTON3.grid(row=7,column=self.__get_button_column(),rowspan=self.__bsy,columnspan=self.__bsx,sticky='WSEN')

        self.BUTTON4=tkinter.Button(self,height=1,bg=self.LABEL_COLOR_1,text="清空",command=self.clear,font=self.ft)
        self.BUTTON4.grid(row=9,column=self.__get_button_column(),rowspan=self.__bsy,columnspan=self.__bsx,sticky='WSEN')

    def create_labels(self):#Labels.
        self.LABEL_OUT1=tkinter.Label(self,relief="raised",font=self.ft,height=1,bg=self.LABEL_COLOR_1,text="脚本名")
        self.LABEL_OUT1.grid(row=1,column=1,rowspan=self.__lsy,columnspan=self.__lsx+2,sticky='WSEN')

    def change_label_text(self,u,string):
        u.config(text=string)
    def do_action(self):
        try:
            content=self.LISTBOX_I.get(0)#从待播报列表获取播放内容.
            content=content[0]
        except:
            content=""
        if(content!=""):
            do_script(content)
            self.LISTBOX_I.delete(0)
            self.after(20,self.do_action)

    def do_repeat(self):
        try:
            content=self.LISTBOX_I.get(self.index)#从待播报列表获取播放内容.
            content=content[0]
        except:
            content=""
        if(content!=""):
            do_script(content)
            self.index=self.index+1
        else:
            self.index=0
        self.after(15,self.do_repeat)

    def create_scroll_listbox(self):#Listbox.
        #创建scrollbar,滚动条.
        self.SCROLLBAR_I=tkinter.Scrollbar(self,orient='vertical')
        self.SCROLLBAR_I.grid(row=3,
                              column=5,
                              rowspan=8,
                              columnspan=1,
                              sticky="WSEN")

        #创建listbox,列表框.并将其yscrollcommand绑定到scrollbar.set.
        self.LISTBOX_I=tkinter.Listbox(self,
                                       bg='black',
                                       fg='white',
                                       selectmode='single',
                                       height=2,
                                       width=2,
                                       yscrollcommand=self.SCROLLBAR_I.set)
        self.LISTBOX_I.grid(row=3,column=1,rowspan=8,columnspan=4,sticky="WSEN")

        self.SCROLLBAR_I.config(command=self.LISTBOX_I.yview)#


    def open_file(self):#打开播报列表,第一列,序号,第二列,名称.为播报内容.
        pt_full=askopenfilename(title="请选择脚本文件",filetypes=[("text files","*.txt")])
        li_name=[]
        with open(pt_full,'r') as f:
            for line in f:
                temp=list(line.strip().split('\n'))
                li_name.append(temp)
        self.LISTBOX_I.delete(0,tkinter.END)
        for t in li_name:
            self.LISTBOX_I.insert(tkinter.END,t)
        temp=os.path.basename(pt_full)
        self.change_label_text(self.LABEL_OUT1,limit_str_len(temp))

    def start_record(self):
        self.q_out.put("start",block=False)

    def clear(self):
        self.index=0
        self.change_label_text(self.LABEL_OUT1,"")
        self.LISTBOX_I.delete(0,tkinter.END)

    def check_quit(self):
        try:
            data=self.q_in.get(block=False)
        except:
            data=""
        if(data=="quit_record"):
            pass
            # self.quit()
        self.after(1,self.check_quit)

    def window_close_handle(self):
        self.q_out.put("quit",block=False)
        print("do quit")
        sys.exit()

    def __init__(self,li,CELL_NUMBER_X,CELL_NUMBER_Y,SCREEN_CELL_NUMBER_X,SCREEN_CELL_NUMBER_Y,master=None):
        self.index=0
        self.INPUT_COLOR="#F0F0F0";self.BACK_COLOR="#CAE9FE";self.LABEL_COLOR_1="#E1F1FF";self.LABEL_COLOR_2="#B1DDFF"#界面颜色相关常量.
        self.CELL_NUMBER_X=CELL_NUMBER_X;self.CELL_NUMBER_Y=CELL_NUMBER_Y#界面大小条件常量.
        self.SCREEN_CELL_NUMBER_X=SCREEN_CELL_NUMBER_X;self.SCREEN_CELL_NUMBER_Y=SCREEN_CELL_NUMBER_Y
        tkinter.Frame.__init__(self,master)
        self.__set_grid_cell_size();self.__set_grid_cell_number(self.CELL_NUMBER_X,self.CELL_NUMBER_Y)
        self.grid();self.__create_frames();self.__set_font();self.__set_button();self.__set_label()
        self.q_in=li[0]
        self.q_out=li[1]
        self.create_buttons()
        self.create_labels()
        self.create_scroll_listbox()
        self.check_quit()
        self.master.protocol("WM_DELETE_WINDOW",self.window_close_handle)

def run_GUI(li):
    root=tkinter.Tk()
    root.title("系统")
    a=GUI(li,7,10,80,80,master=root)#GUI其实是Frame的继承.界面宽度,界面高度,屏幕网格细度（X,Y）
    img_str=b'iVBORw0KGgoAAAANSUhEUgAAAHcAAAB3CAYAAAA5Od+KAAAABGdBTUEAALGOfPtRkwAAACBjSFJNAACHDwAAjA8AAP1SAACBQAAAfXkAAOmLAAA85QAAGcxzPIV3AAAKL2lDQ1BJQ0MgUHJvZmlsZQAASMedlndUVNcWh8+9d3qhzTDSGXqTLjCA9C4gHQRRGGYGGMoAwwxNbIioQEQREQFFkKCAAaOhSKyIYiEoqGAPSBBQYjCKqKhkRtZKfHl57+Xl98e939pn73P32XuftS4AJE8fLi8FlgIgmSfgB3o401eFR9Cx/QAGeIABpgAwWempvkHuwUAkLzcXerrICfyL3gwBSPy+ZejpT6eD/0/SrFS+AADIX8TmbE46S8T5Ik7KFKSK7TMipsYkihlGiZkvSlDEcmKOW+Sln30W2VHM7GQeW8TinFPZyWwx94h4e4aQI2LER8QFGVxOpohvi1gzSZjMFfFbcWwyh5kOAIoktgs4rHgRm4iYxA8OdBHxcgBwpLgvOOYLFnCyBOJDuaSkZvO5cfECui5Lj25qbc2ge3IykzgCgaE/k5XI5LPpLinJqUxeNgCLZ/4sGXFt6aIiW5paW1oamhmZflGo/7r4NyXu7SK9CvjcM4jW94ftr/xS6gBgzIpqs+sPW8x+ADq2AiB3/w+b5iEAJEV9a7/xxXlo4nmJFwhSbYyNMzMzjbgclpG4oL/rfzr8DX3xPSPxdr+X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KW/4duXid621khsNBObJgB+lSnnagxA4BfkFgcfX1hZuEbP8du/hK86GsN/aAvSLhB+qhOX1nkbjx3MvU7sRltlv+G4YrHXk3iaeudJkkC8l2OSXCbHlEZhoLwrncCn//mR2do0LtzS7uO/3GrF2ZNAx+i9aJc2NP0o/CPOtH79EGIKL5473dsfMLz8sLzX8RX1syaOtpCaDPOKB5LGHhdg2HwInE2nZUn7+eHb2CVo2q7h/7TVi3QBdG/JoXDn92cFLVNO7SOY24NMI1Z3E7RGU3odz1NSIvGAaecWDEuf/R4iDz0HgLKKMLiRPGBduNnHf6zViTXdpO3NmQhmtVv3coOf5wPwYR0PXMm7T3PblB8sdQmnqi6dOAPnGzaqLvxTC+w8haJikSU9nZx+3gEuziPtm7+EfJ5LInR1fJvcoOnfFZePiGtQQb0/4pNHg3qWGgDxcjc3M11F6SxHpLeVxSyZFXdzXeg9f6icaNzfu6I4KIcfigrivtSkvYGrzBMiIuE+BvPwd3NF3lkDgfkTd0f690ToUXXFfzsp75HtFv+KZuIolAUFn4EJqnEj2YyEoZZOH7+rh9o1CHPlSEJ0mJfdomUStnft81rBr9ir6/H9qPl4K6CMrOUaUQBv49kwpF81H+/cDIUb+0uUqikrJnd8nd9h3SvBKCDsgJmyz8eJuIXa6EEknab4NNeLi3tV3SMJuRc/6TPPzPKJ21RnRmkFecyfJ08tQ93aXoWUPI26WYR4EvqjlOqx/xCDv0+OI9jyvG9o/hUiKeMmNCdtyIO8PeYn+9R/EHUTnRb0pFKPZ+fd2wQ/ZyTNi4rY/vuT5tDaiTjFx2x8lZWjv4p8aE7f9UQqnxwgSHYyJ285gh1Yj0gMkNsXEbWegOaSkShLsNcfEbX90Rn27+26XqywmbvsjC21c82G4mLjtjB5SnhNPZL41NCZuO+MktG9nWk8kxMRtR8CZSkJ9W/3W0Ji47YghUg7sJs0XSJrExG1H2ImK/7umBtH/AdW6esmu5JL5AAAAAElFTkSuQmCC'
    img_data=base64.b64decode(img_str)
    with open('ico.png','wb') as f:
        f.write(img_data)
    root.iconphoto(False,tkinter.PhotoImage(file='ico.png'))
    x,y=a.get_GUI_size()
    root.geometry(set_window(x,y))
    root.resizable(height=False,width=False)#窗口是否可以调整大小.
    root.attributes("-topmost",1);root.attributes("-topmost",0)#置顶后取消,让窗口出现在最顶层.
    root.mainloop()#进入消息循环.

class MONITOR():
    def __init__(self,li):
        self.q_in=li[1]
        self.q_out=li[0]
        self.flag_record=False
        self.flag_quit=False
        self.m=pynput.mouse.Listener(on_move=self.move,on_click=self.click,on_scroll=self.scroll)
        self.m.start()
        self.k=pynput.keyboard.Listener(on_press=self.press,on_release=self.release)
        self.k.start()
        self.m.join()#此处要放在k.start()之后,k.join()之前.
        self.k.join()
    def move(self,x,y):
        try:
            data=self.q_in.get(block=False)
        except:
            data=""
        if(data=="start"):
            self.flag_record=True
            self.out=sys.stdout
            ticks=datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
            sys.stdout=open(r".\result\scripts→"+"_"+ticks+".txt","w")
        elif(data=="quit"):
            self.flag_quit=True
        if(self.flag_quit):
            self.m.stop()
            self.k.stop()
    def click(self,x,y,button,pressed):
        if(self.flag_record):
            print("m-c:{}-{}-{}".format((x,y),button,pressed))
    def scroll(self,x,y,dx,dy):
        if(self.flag_record):
            print("m-s:{}-{}".format((x,y),(dx,dy)))
    def press(self,key):
        if(self.flag_record):
            print("k-p:{}".format(key))
    def release(self,key):
        if key==pynput.keyboard.Key.esc:#如果检测到esc按键释放.
            self.q_out.put("quit_record",block=False)
            self.flag_record=False#如果检测到esc按键,则结束打印.
            sys.stdout.close()
            sys.stdout=self.out
        else:
            if(self.flag_record):
                print("k-r:{}".format((key)))

def run_monitor(q):
    MONITOR(q)

if __name__=='__main__':
    import multiprocessing
    from multiprocessing import Process,Queue
    multiprocessing.freeze_support()
    q_key_to_gui=Queue()
    q_gui_to_key=Queue()
    li_q=[q_key_to_gui,q_gui_to_key]
    process=[Process(target=run_GUI,args=(li_q,)),
             Process(target=run_monitor,args=(li_q,))]
    [p.start() for p in process]
    [p.join() for p in process]

    # os.system("pause")
